//这个是mongodb二阶段提交的例子

//Initialize Source and Destination Accounts
db.accounts.insert(
    [{
        _id: "A",
        balance: 1000,
        pendingTransactions: []
    }, {
        _id: "B",
        balance: 1000,
        pendingTransactions: []
    }]
);

//Initialize Transfer Record
db.transactions.insert({
    _id: 1,
    source: "A",
    destination: "B",
    value: 100,
    state: "initial",
    lastModified: new Date()
});

//1.Retrieve the transaction to start.
var t = db.transactions.findOne({
    state: "initial"
});
//2.Update transaction state to pending.
db.transactions.update({
    _id: t._id,
    state: "initial"
}, {
    $set: {
        state: "pending"
    },
    $currentDate: {
        lastModified: true
    }
});

//3.Apply the transaction to both accounts.
db.accounts.update({
    _id: t.source,
    pendingTransactions: {
        $ne: t._id
    }
}, {
    $inc: {
        balance: -t.value
    },
    $push: {
        pendingTransactions: t._id
    }
});

db.accounts.update({
    _id: t.destination,
    pendingTransactions: {
        $ne: t._id
    }
}, {
    $inc: {
        balance: t.value
    },
    $push: {
        pendingTransactions: t._id
    }
});

//4.Update transaction state to applied.
db.transactions.update({
    _id: t._id,
    state: "pending"
}, {
    $set: {
        state: "applied"
    },
    $currentDate: {
        lastModified: true
    }
});

//5.Update both accounts’ list of pending transactions.
db.accounts.update({
    _id: t.source,
    pendingTransactions: t._id
}, {
    $pull: {
        pendingTransactions: t._id
    }
});
db.accounts.update({
    _id: t.destination,
    pendingTransactions: t._id
}, {
    $pull: {
        pendingTransactions: t._id
    }
});

//6.Update transaction state to done.
db.transactions.update({
    _id: t._id,
    state: "applied"
}, {
    $set: {
        state: "done"
    },
    $currentDate: {
        lastModified: true
    }
});
